package com.hmyd.hmyd_android.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.crypto.Cipher;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import com.google.common.io.BaseEncoding;
import com.hmyd.hmyd_android.AppBasic;
import com.hmyd.hmyd_android.commons.Constants;
import com.hmyd.hmyd_android.dto.JfMallItemDto;
import com.hmyd.hmyd_android.ui.WebActivity;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.util.LogUtils;

/**
 * 工具类
 */
public class Utils {
	// 手机分辨率宽高
	public static int screenHeight_;
	public static int screenWidth_;
	static final String LOG_TAG = "PullToRefresh";
	private static final String downloadParentFileName = "Hmyd";

	/**
	 * 验证手机号码格式表达式
	 */
	public static Pattern MobilePattern = Pattern.compile("^(0|86|17951)?(13[0-9]|15[012356789]|17[0678]|18[0-9]|14[57])[0-9]{8}$");

	/**
	 * 获取屏幕分辨率
	 * 
	 * @param context
	 */
	public static void windowScreenSize(Context context) {
		DisplayMetrics outMetrics = new DisplayMetrics();
		((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
		screenHeight_ = outMetrics.heightPixels;
		screenWidth_ = outMetrics.widthPixels;
	}

	/**
	 * 获取版本名称
	 * 
	 * @param context
	 * @return
	 */
	public static String getVersionName(Context context) {
		try {
			String pkName = context.getPackageName();
			String versionName = context.getPackageManager().getPackageInfo(pkName, 0).versionName;
			LogUtils.d(versionName);

			return versionName;
		} catch (Exception e) {

		}
		return null;
	}

	/**
	 * 获取友盟渠道号
	 * 
	 * @param context
	 * @return
	 */
	public static String getUmengChannel(Activity context) {
		Object value = null;

		PackageManager packageManager = context.getPackageManager();
		ApplicationInfo applicationInfo;

		try {
			applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), 128);

			if (applicationInfo != null && applicationInfo.metaData != null) {
				value = applicationInfo.metaData.get("UMENG_CHANNEL");
				if (value != null) {
					LogUtils.d(value.toString());
					return value.toString();
				}
			}
		} catch (NameNotFoundException e) {

		}

		return null;
	}

	/**
	 * 货币转换 1000000 return 1百万 10000 return 1万 1000 return 1千
	 * 
	 * @param amount
	 * @return
	 */
	public static HashMap<String, String> amountConversionMap(long amount) {
		HashMap<String, String> map = new HashMap<String, String>();

		if (amount >= 1000000) {
			map.put("amount", amount / 1000000 + "");
			map.put("amoun_unit", "百万");
			return map;
		}

		if (amount >= 10000) {
			map.put("amount", amount / 10000 + "");
			map.put("amoun_unit", "万元");
			return map;
		}

		if (amount >= 1000) {
			map.put("amount", amount / 1000 + "");
			map.put("amoun_unit", "千元");
			return map;
		}

		map.put("amount", amount + "");
		map.put("amoun_unit", "元");
		return map;
	}

	/**
	 * 1000000 return 1百万 10000 return 1万 1000 return 1千
	 * 
	 * @param amount
	 * @return
	 */
	public static String amountConversion(long amount) {
		if (amount >= 1000000) {
			return amount / 1000000 + "百万";
		}

		if (amount >= 10000) {
			return amount / 10000 + "万元";
		}

		if (amount >= 1000) {
			return amount / 1000 + "千元";
		}

		return amount + "元";
	}

	/**
	 * 10000 return 10,000
	 * 
	 * @param amount
	 * @return
	 */
	public static String amountConversionFormat(long amount) {
		return NumberFormat.getInstance().format(amount);
	}

	/**
	 * 10000 return 10,000
	 * 
	 * @param amount
	 * @return
	 */
	public static String amountConversionFormat(double amount) {
		return NumberFormat.getInstance().format(amount);
	}

	/**
	 * 1 Year 1年 1 Month 1个月 1 Day 1天
	 * 
	 * @param period
	 * @param periodUnit
	 * @return
	 */
	public static String periodConversion(int period, String periodUnit) {
		if ("Year".equals(periodUnit)) {
			return period + "年";
		}

		if ("Month".equals(periodUnit)) {
			return period + "个月";
		}

		if ("Day".equals(periodUnit)) {
			return period + "天";
		}

		return period + "";
	}

	/**
	 * 1 Year 1年 1 Month 1个月 1 Day 1天
	 * 
	 * @param period
	 * @param periodUnit
	 * @return
	 */
	public static String periodConversion(String periodUnit) {
		if ("Year".equals(periodUnit)) {
			return "年";
		}

		if ("Month".equals(periodUnit)) {
			return "个月";
		}

		if ("Day".equals(periodUnit)) {
			return "天";
		}

		return "";
	}
	
	
	/**
	 * ep: xx月xx日 xx:xx
	 * 
	 * get time ,only have month,date,hour and minutes
	 * @param time
	 * @return
	 */
	public static String getDateStringMonthDayTime(long time) {
		
		Calendar cal = Calendar.getInstance();
		cal.setTimeInMillis(time);
		StringBuilder builder = new StringBuilder();
		int month = cal.get(Calendar.MONTH)+1;
		builder.append(month);
		builder.append("月");
		builder.append(cal.get(Calendar.DATE));
		builder.append("日");
		builder.append("  ");
		builder.append(cal.get(Calendar.HOUR_OF_DAY));
		builder.append(":");
		builder.append(cal.get(Calendar.MINUTE));
		return builder.toString();
	}

	/**
	 * 123123123 2015-05-18 10:54:27
	 * 
	 * @param time
	 * @return
	 */
	public static String getDateString(long time) {
		SimpleDateFormat myFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		return myFmt.format(new Date(time));
	}

	public static String getDateStringMinute(long time) {
		SimpleDateFormat myFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm");

		return myFmt.format(new Date(time));
	}

	/**
	 * ep: xx月xx日
	 * @param time longtime
	 * @return
	 */
	public static String getDateStringMonthAndDay(long time) {
		Calendar cal = Calendar.getInstance();
		cal.setTimeInMillis(time);
		StringBuilder sb = new StringBuilder();
		sb.append(cal.get(Calendar.MONTH)+1);
		sb.append("月");
		sb.append(cal.get(Calendar.DAY_OF_MONTH));
		sb.append("日");
		return sb.toString();
	}
	
	/**
	 * 123123123 2015-05-18
	 * 
	 * @param time
	 * @return
	 */
	public static String getDateStringDay(long time) {
		SimpleDateFormat myFmt = new SimpleDateFormat("yyyy-MM-dd");

		return myFmt.format(new Date(time));
	}

	public static boolean isDouble(String value) {
		try {
			Double.parseDouble(value);
			return true;
		} catch (NumberFormatException e) {
			return false;
		}
	}

	/**
	 * 跳转到内部WebView
	 * 
	 * @param context
	 * @param url
	 * @param title
	 */
	/*
	 * public static void jumpURL(Context context, String url, String title) {
	 * if (TextUtils.isEmpty(url) || "#".equals(url)) { return; }
	 * 
	 * Intent intent = new Intent(context, WebActivity.class);
	 * intent.putExtra("url", url); intent.putExtra("name", title);
	 * context.startActivity(intent); }
	 */
	
	
	public static void jumpURL(Context context, String url, String title,String iconUrl,boolean isRightShow) {
		if (TextUtils.isEmpty(url) || "#".equals(url)) {
			return;
		}
		
		Intent intent = new Intent(context, WebActivity.class);
		intent.putExtra("url", url);
		intent.putExtra("name", title);
		intent.putExtra("iconUrl", iconUrl);
		intent.putExtra("isRightShow", isRightShow);
		context.startActivity(intent);
	}
	
	public static void jumpURLS(Context context, String url, String title,String iconUrl,boolean isRightShow, boolean isQRShare) {
		if (TextUtils.isEmpty(url) || "#".equals(url)) {
			return;
		}
		
		Intent intent = new Intent(context, WebActivity.class);
		intent.putExtra("url", url);
		intent.putExtra("name", title);
		intent.putExtra("iconUrl", iconUrl);
		intent.putExtra("isRightShow", isRightShow);
		intent.putExtra("isQRShare", isQRShare);
		context.startActivity(intent);
	}

	/**
	 * 下载文件
	 */
	public static void jumpDownFile(final Activity activity, String url) {
		if (TextUtils.isEmpty(url)) {
			return;
		}
		Log.d("sss", url);
		String fileName = url.substring(url.lastIndexOf("/"), url.length());
		String filePath = getDownPath(activity) + fileName;

		AppBasic.getHttpUtils().download(url, filePath, true, true, new RequestCallBack<File>() {

			@Override
			public void onStart() {
				super.onStart();
			}
			
			@Override
			public void onLoading(long total, long current, boolean isUploading) {
				super.onLoading(total, current, isUploading);
			}
			
			@Override
			public void onSuccess(ResponseInfo<File> responseInfo) {
				Log.i("jumpDownFile","下载成功，路径为:"+responseInfo.result.getPath());
				MyToast.showHMToast(activity, true, "download path:"+responseInfo.result.getPath());
			}
			
			@Override
			public void onFailure(HttpException error, String msg) {
				Log.e("jumpDownFile","下载失败:"+msg);
				MyToast.showHMToast(activity, false, "下载失败:"+msg);
			}
		});
	}
	
	/**
	 * 获取文件下载父路径
	 * @param context
	 * @return
	 */
	public static String getDownPath(Context context) {
		if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			return Environment.getExternalStorageDirectory()+File.separator+downloadParentFileName;
		} else {
			return context.getDir(downloadParentFileName, Context.MODE_PRIVATE).getPath();
		}
	}

	/*	*//**
	 * 9.658 return 9.65
	 */
	/*
	 * public static BigDecimal scale(double scale){ return new
	 * BigDecimal(scale).setScale(2, BigDecimal.ROUND_DOWN); }
	 *//**
	 * 9.658 return 9.65
	 */
	public static BigDecimal scale(BigDecimal scale) {
		return scale.setScale(2, BigDecimal.ROUND_DOWN);
	}

	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	/**
	 * 13817124233 138****4233
	 * 
	 * @param phone
	 * @return
	 */
	public static String hidePhone(String phone) {
		return phone.substring(0, 3) + "****" + phone.substring(7, phone.length());
	}

	public static boolean regPatternsPassword(Context context, String password) {
		if (password.length() < 6 || password.length() > 20) {
			MyToast.showToast(context, "密码长度只能在6-20位字符之间");
			return true;
		}

		Pattern sameCharsPattern = Pattern.compile("(\\w)(\\1)+");
		if (sameCharsPattern.matcher(password).matches()) {
			MyToast.showToast(context, "密码不能为同一个字符");
			return true;
		}

		Pattern containsCharsPattern = Pattern.compile("^[0-9]*$");
		Pattern containsNumberPattern = Pattern.compile("^[a-zA-Z]+$");
		if (containsCharsPattern.matcher(password).matches()
				|| containsNumberPattern.matcher(password).matches()) {
			MyToast.showToast(context, "密码需要包含字母和数字");
			return true;
		}

		return false;
	}

	/**
	 * 跳转到webview
	 * 
	 * @param url
	 */
	public static void jumpExplorer(Context context, String url) {
		if (TextUtils.isEmpty(url) || "#".equals(url)) {
			return;
		}

		Intent intent = new Intent();
		intent.setAction("android.intent.action.VIEW");
		Uri content_url = Uri.parse(url);
		intent.setData(content_url);
		context.startActivity(intent);
	}

	public static String getTime() {

		SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
		String date = simpleFormat.format(System.currentTimeMillis());
		return date;

	}

	// 生成请求签名
	public static String getSign(Context context, String sign) {

		String signMd5 = md5(sign).toUpperCase();
		String newEncryptStr = null;

		try {
			CertificateFactory cff = CertificateFactory.getInstance("X.509");
			AssetManager am = context.getResources().getAssets();
			InputStream is = am.open("hmyd_app_pub.cer");
			Certificate cf = cff.generateCertificate(is);
			PublicKey pk1 = cf.getPublicKey(); // 得到证书文件携带的公钥
			Cipher c1 = Cipher.getInstance("RSA/ECB/PKCS1Padding"); // 定义算法：RSA
			c1.init(Cipher.ENCRYPT_MODE, pk1);
			byte[] encryptStr = c1.doFinal(signMd5.getBytes()); // 加密后的数据
			newEncryptStr = BaseEncoding.base64().encode(encryptStr);

		} catch (Exception e) {

		}

		return newEncryptStr;

	}

	// 生成请求签名解密
	public static String getSignDecrypt(Context context, String key) {
		String decryptStr = null;

		try {
			CertificateFactory cff = CertificateFactory.getInstance("X.509");
			Certificate cf = cff.generateCertificate(context.getAssets().open("hmyd_app_pub.cer"));
			PublicKey pk2 = cf.getPublicKey();

			Cipher c2 = Cipher.getInstance("RSA/ECB/PKCS1Padding");
			c2.init(Cipher.DECRYPT_MODE, pk2);
			byte[] decryptStrArr = c2.doFinal(BaseEncoding.base64().decode(key)); // 解密后的数据

			decryptStr = (new String(decryptStrArr, "UTF8"));
		} catch (Exception e) {

		}

		return decryptStr;

	}

	public static String md5(String string) {
		byte[] hash;
		try {
			hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException("Huh, MD5 should be supported?", e);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException("Huh, UTF-8 should be supported?", e);
		}

		StringBuilder hex = new StringBuilder(hash.length * 2);
		for (byte b : hash) {
			if ((b & 0xFF) < 0x10)
				hex.append("0");
			hex.append(Integer.toHexString(b & 0xFF));
		}
		return hex.toString();
	}

	public static void closeBoard(Activity mActivity) {
		((InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE))
				.hideSoftInputFromWindow(mActivity.getCurrentFocus().getWindowToken(),
						InputMethodManager.HIDE_NOT_ALWAYS);
	}

	/**
	 * 计算金额
	 * 
	 * @param argStr
	 * @return
	 */
	public static String getFloatDotStr(String argStr) {
		float arg = Float.valueOf(argStr);
		DecimalFormat fnum = new DecimalFormat("##0.00");
		return fnum.format(arg);
	}

	/**
	 * 判断应用程序是否安装
	 * 
	 * @param context
	 * @param packageName
	 *            应用程序安装包名
	 * @return
	 */
	public static boolean isAppInstalled(Context context, String packageName) {
		PackageInfo packageInfo = null;
		try {
			// 获取安装包信息
			packageInfo = context.getPackageManager().getPackageInfo(packageName, 0);
		} catch (NameNotFoundException e) {
			packageInfo = null;
			e.printStackTrace();
		}

		if (null == packageInfo) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * 打开客服临时会话(如果应用已安装， 未安装的话则提示是否安装)
	 * 
	 * @param context
	 * @param packageName
	 *            需判断的应用程序包名
	 * @param uin
	 *            客服id(QQ号)
	 */
	public static void openSession(final Context context, final String packageName, String uin) {
		if (isAppInstalled(context, packageName)) { // 如果安装应用则打开
			String url = null;
			if (!TextUtils.isEmpty(uin)) {
				// 开启一个临时会话(客服咨询)
				url = "mqqwpa://im/chat?chat_type=wpa&uin=" + uin; // 打开客服临时QQ
				context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
			} else {
				/*
				 * // JS实现打开公众号 // url =
				 * "http://weixin.qq.com/r/Z0PK0pzEncHirdix9xZ1"; url =
				 * "weixin://qr/Z0PK0pzEncHirdix9xZ1"; WebView webView = new
				 * WebView(context); //设置可以使用Javascript
				 * webView.getSettings().setJavaScriptEnabled(true);
				 * webView.loadUrl(url);
				 */

				Intent intent = new Intent();

				ComponentName cmp = new ComponentName(packageName, Constants.WEIXIN_LAUCHERUI);
				intent.setAction(Intent.ACTION_MAIN);
				intent.addCategory(Intent.CATEGORY_LAUNCHER);
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.setComponent(cmp);
				((Activity) context).startActivityForResult(intent, 0);
			}
		} else { // 未安装应用 判断是否去 market 市场安装
			new AlertDialog.Builder(context).setTitle("提示").setMessage("未安装应用程序，是否安装？")
					.setNegativeButton("取消", new OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {

						}
					}).setPositiveButton("确认", new OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							String url = "market://details?id=" + packageName;
							context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
						}
					}).show();
		}
	}

	/**
	 * 从 Assets 文件夹中获取图片
	 * 
	 * @param c
	 * @param assetName
	 *            文件名称
	 * @return null 文件不存在
	 */
	public static Bitmap getBitmapFromAssets(Activity activity, String assetName) {
		InputStream input = null;
		Bitmap bmp = null;
		try {
			input = activity.getAssets().open(assetName);
			bmp = BitmapFactory.decodeStream(input);
		} catch (IOException e) {
			bmp = null;
			e.printStackTrace();
		} finally {
			try {
				input.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return bmp;
	}

	/**
	 * 获取SDK版本
	 * 
	 * @return
	 */
	public static int getSDKVersion() {
		return Build.VERSION.SDK_INT;
	}

	/* 控制台统一输出信息 start */

	// 是否打印标志
	private static boolean isPrintMessage_;

	public static void isPrintMessage(boolean isprint) {
		isPrintMessage_ = isprint;
	}

	/**
	 * 控制台统一打印
	 * 
	 * @param obj
	 */
	public final static void printOutToConsole(Object obj) {
		if (isPrintMessage_) {
			if (obj instanceof String) {
				printOutToConsole((String) obj);
			} else if (obj instanceof byte[]) {
				printOutToConsole((byte[]) obj);
			} else {
				System.out.println(obj);
			}
		}
	}

	/**
	 * @param s
	 */
	public final static void printOutToConsole(String s) {
		if (isPrintMessage_) {
			int length = s.length();
			int offset = 3000;
			if (length > offset) {// 解决报文过长，打印不全的问题
				int n = 0;
				for (int i = 0; i < length; i += offset) {
					n += offset;
					if (n > length)
						n = length;
					System.out.println(s.substring(i, n));
				}
			} else {
				System.out.println(s);
			}
		}
	}

	/**
	 * @param byts
	 */
	public final static void printOutToConsole(byte[] byts) {
		if (isPrintMessage_) {
			if (byts == null) {
				return;
			}
			for (int i = 0; i < byts.length; i++) {
				System.out.print("[" + i + "]" + " : \t");
				System.out.println(byts[i]);
			}
		}
	}

	/**
	 * 异常统一打印
	 * 
	 * @param e
	 */
	public final static void printException(Exception e) {
		if (isPrintMessage_) {
			e.printStackTrace();
		}
	}

	/* 信息输出 end */

	/* 网络判断 start */
	/**
	 * 获取网络链接类型信息
	 * 
	 * @return
	 */
	public static int getConnectedType(Context context) {
		ConnectivityManager conn = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netInfo = conn.getActiveNetworkInfo();
		if (null == netInfo || !netInfo.isAvailable()) {
			return netInfo.getType();
		}
		return -1;
	}

	/**
	 * 判断网络是否可用
	 * 
	 * @return
	 */
	public static boolean isConnectByNet(Context context) {
		ConnectivityManager conn = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netInfo = conn.getActiveNetworkInfo();
		if (null == netInfo || !netInfo.isAvailable()) {
			return false;
		}
		return true;
	}

	/**
	 * 判断wifi是否可用
	 * 
	 * @return
	 */
	public static boolean isConnectByWifi(Context context) {
		ConnectivityManager conn = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo wifiInfo = conn.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		if (null == wifiInfo || !wifiInfo.isAvailable()) {
			return false;
		}
		return true;
	}

	/**
	 * 判断Mobile网络是否可用
	 * 
	 * @return
	 */
	public static boolean isConnectByMobile(Context context) {
		ConnectivityManager conn = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo mobileInfo = conn.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		if (null == mobileInfo || !mobileInfo.isAvailable()) {
			return false;
		}
		return true;
	}

	/* 网络判断 end */

	/**
	 * 获取屏幕宽度
	 * 
	 * @param context
	 * @return
	 */
	public static int getScreenWith(Context context) {
		DisplayMetrics dm = new DisplayMetrics();
		dm = context.getApplicationContext().getResources().getDisplayMetrics();
		return dm.widthPixels;
	}

	/**
	 * 获取屏幕高度
	 * 
	 * @param context
	 * @return
	 */
	public static int getScreenHeight(Context context) {
		DisplayMetrics dm = new DisplayMetrics();
		dm = context.getApplicationContext().getResources().getDisplayMetrics();
		return dm.heightPixels;
	}

	public static void warnDeprecation(String depreacted, String replacement) {
		Log.w(LOG_TAG, "You're using the deprecated " + depreacted + " attr, please switch over to " + replacement);
	}
	
	/**
	 * 积分商城根据一个item的createdTime进行冒泡排序
	 * 
	 * @param datas
	 * @param isDesc
	 *            true:从大到小, false:从小到大
	 * @return
	 */
	public static void jfmallSortByTime(List<JfMallItemDto> datas,
			boolean isDesc) {
		JfMallItemDto dto = null;
		for (int i = 0; i < datas.size() - 1; i++) {
			for (int j = i; j < datas.size(); j++) {
				if (isDesc) {
					if (datas.get(i).createdTime < datas.get(j).createdTime) {
						dto = datas.get(i);
						datas.add(i, datas.get(j));
						datas.add(j, dto);
					}
				} else {
					if (datas.get(i).createdTime > datas.get(j).createdTime) {
						dto = datas.get(i);
						datas.add(i, datas.get(j));
						datas.add(j, dto);
					}
				}
			}

		}
	}

	/**
	 * 判断当前字符是否是表情字符
	 * 
	 * @param codePoint
	 * @return
	 */
	public static boolean isEmojiCharacter(char codePoint) {
		return (codePoint == 0x0) ||
                (codePoint == 0x9) ||
                (codePoint == 0xA) ||
                (codePoint == 0xD) ||
                ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
                ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) ||
                ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF));
	}

	/**
	 * 判断当前字符
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isEmojiCharacter(String str) {
		if (TextUtils.isEmpty(str)) {
			return false;
		}
		for (int i = 0; i < str.length(); i++) {
			if (!isEmojiCharacter(str.charAt(i))) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 改变字体大小和颜色
	 * @param str
	 * @param view
	 * @param isChangeColor
	 */
	public static void changeTextSize(String str, TextView view, int color) {
		int start = 0;
		int end = 0;
		if (str.contains("[") && str.contains("]")) {
			start = str.indexOf("[");
			end = str.indexOf("]");
			
			str = str.replace("[", "").replace("]", "");
			
			Spannable WordtoSpan = new SpannableString(str);
			
//			WordtoSpan.setSpan(new RelativeSizeSpan(1.5f), start, end - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			if (color != 0) {
				WordtoSpan.setSpan(new ForegroundColorSpan(color), start, end - 1,
						Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			}
			view.setText(WordtoSpan);
		} else {
			view.setText(str);
		}
	}
	

	/**
	 * 通过指定单位，返回一个像素值 xml单位适配
	 * 
	 * @param context
	 * @param unit
	 *            单位
	 * @param value
	 *            数值
	 * @return
	 */
	public static float getRawSize(Context context, int unit, float value) {
		Resources res = context.getResources();
		return TypedValue.applyDimension(unit, value, res.getDisplayMetrics());
	}
	
	/**
	 * 替换完字符里所有空白之后，判断是否字符串是否由全0组成
	 * @param str
	 * @return
	 */
	public static boolean isAllZero(String str) {
		if(TextUtils.isEmpty(str)) {
			return false;
		}
		String str2 = str.trim().replace(" ", "");
		String regex = "^0+$";
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(str2);
		return matcher.matches();
	}
	
	/**
	 * list集合转换成字符串
	 * @param list
	 * @return
	 */
	public static String listToString(List<String> list) {
		StringBuffer buffer = new StringBuffer();
		buffer.append("[");
		for (String string : list) {
			buffer.append(string);
			buffer.append(",");
		}
		buffer.deleteCharAt(buffer.length()-1);
		buffer.append("]");
		return buffer.toString();
	}
	
	/**
	 * 保留两位小数
	 * @param value
	 * @return
	 */
	public static String CovertTwoDecimal(Object value) {
		DecimalFormat df = new DecimalFormat("######0.00");
		return df.format(Double.parseDouble((String) value));
	}
	
	/**
	 * 小数转百分数
	 * 
	 */
	public static String changePointToPercent(Double point) {
        return String.valueOf(point*100);
    }
	
}
